﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>物料流转数据分析</title>
    <link rel="stylesheet" href="../../scripts/layui-v2.5.6/layui/css/layui.css">
    <script src="../../scripts/jquery-3.4.1.min.js"></script>
    <script src="../../scripts/layui-v2.5.6/layui/layui.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #f2f2f2;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }
        
        /* 筛选区域样式 */
        .filter-container {
            background: #fff;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .filter-form {
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .filter-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .filter-label {
            font-size: 14px;
            color: #333;
            white-space: nowrap;
        }
        
        .main-container {
            display: flex;
            gap: 20px;
            min-height: calc(100vh - 140px);
            height: calc(100vh - 140px);
        }
        .left-panel {
            flex: 1;
            background: #fff;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
        }
        .right-panel {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 20px;
            height: 100%;
        }
        .chart-container {
            background: #fff;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            flex: 1;
            display: flex;
            flex-direction: column;
            min-height: 0;
        }
        .chart-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #333;
            padding-left: 10px;
            border-left: 4px solid #009688;
            text-align: center;
            flex-shrink: 0;
        }
        .chart {
            width: 100%;
            flex: 1;
            min-height: 0;
        }
        .pie-chart {
            width: 100%;
            flex: 1;
            min-height: 0;
        }

    </style>
</head>
<body>
    <!-- 筛选区域 -->
    <div class="filter-container">
        <form class="layui-form filter-form" lay-filter="searchForm">
            <div class="filter-item">
                <label class="filter-label">单据类型：</label>
                <select name="documentType" lay-verify="" lay-search="">
                    <option value="">请选择单据类型</option>
                    <option value="产品生产">产品生产</option>
                    <option value="生产领料" selected>生产领料</option>
                </select>
            </div>
            
            <div class="filter-item">
                <button type="button" class="layui-btn layui-btn-normal" id="searchBtn">
                    <i class="layui-icon layui-icon-search"></i> 搜索
                </button>
                <button type="button" class="layui-btn layui-btn-primary" id="resetBtn">
                    <i class="layui-icon layui-icon-refresh"></i> 重置
                </button>
            </div>
            
            <div class="filter-item" style="margin-left: auto;">
                <span id="dataTypeHint" style="color: #009688; font-size: 12px;">
                    <i class="layui-icon layui-icon-tips"></i> 生产领料显示领料数据，产品生产显示工单数据
                </span>
            </div>
        </form>
    </div>

    <div class="main-container">
        <!-- 左侧饼状图 -->
        <div class="left-panel">
            <div class="chart-title">物料流转占比分析</div>
            <div id="pieChart" class="pie-chart"></div>
        </div>

        <!-- 右侧图表 -->
        <div class="right-panel">
            <!-- 柱状图 -->
            <div class="chart-container">
                <div class="chart-title">物料流转柱状图统计</div>
                <div id="barChart" class="chart"></div>
            </div>

            <!-- 折线图 -->
            <div class="chart-container">
                <div class="chart-title">物料流转趋势分析</div>
                <div id="lineChart" class="chart"></div>
            </div>
        </div>
    </div>

    <script>
        // 使用layui
        layui.use(['form', 'layer'], function(){
            var form = layui.form;
            var layer = layui.layer;
            
            // 获取默认选中的单据类型
            var defaultDocumentType = "生产领料";
            
            // 设置默认值并更新标题
            form.val('searchForm', {
                'documentType': defaultDocumentType
            });
            updatePageTitles(defaultDocumentType);
            
            // 初始化所有图表，传入默认的单据类型
            initPieChart(defaultDocumentType);
            initBarChart(defaultDocumentType);
            initLineChart(defaultDocumentType);
            
            // 搜索按钮事件
            $('#searchBtn').on('click', function(){
                var documentType = $('select[name="documentType"]').val();
                
                // 显示加载提示
                var loadIndex = layer.load(1, {
                    shade: [0.1,'#fff']
                });
                
                // 重新加载图表数据
                refreshCharts(documentType, function(){
                    layer.close(loadIndex);
                    var message = '';
                    if (documentType === '产品生产') {
                        message = '已切换至【产品生产】数据展示（生产工单数据）';
                    } else if (documentType === '生产领料') {
                        message = '已切换至【生产领料】数据展示（生产领料数据）';
                    } else {
                        message = '数据已更新（生产领料数据）';
                    }
                    layer.msg(message, {icon: 1, time: 2000});
                });
            });
            
            // 重置按钮事件
            $('#resetBtn').on('click', function(){
                // 重置表单
                form.val('searchForm', {
                    'documentType': ''
                });
                
                // 重新加载图表数据
                var loadIndex = layer.load(1, {
                    shade: [0.1,'#fff']
                });
                
                refreshCharts('', function(){
                    layer.close(loadIndex);
                    layer.msg('已重置为默认数据展示（生产领料数据）', {icon: 1, time: 2000});
                });
            });
            
            // 表单提交事件（回车搜索）
            form.on('submit(searchForm)', function(data){
                $('#searchBtn').trigger('click');
                return false;
            });
        });
        
        // 刷新所有图表数据
        function refreshCharts(documentType, callback) {
            var completed = 0;
            var total = 3;
            
            function checkComplete() {
                completed++;
                if (completed === total && callback) {
                    callback();
                }
            }
            
            // 更新页面固定标题
            updatePageTitles(documentType);
            
            // 重新初始化所有图表
            initPieChart(documentType, checkComplete);
            initBarChart(documentType, checkComplete);  
            initLineChart(documentType, checkComplete);
        }
        
        // 更新页面固定标题
        function updatePageTitles(documentType) {
            var suffix = documentType ? '-' + documentType : '';
            
            // 更新各个图表容器的标题
            $('.left-panel .chart-title').text('物料流转占比分析' + suffix);
            $('.right-panel .chart-container:first .chart-title').text('物料流转柱状图统计' + suffix);
            $('.right-panel .chart-container:last .chart-title').text('物料流转趋势分析' + suffix);
            
            // 更新数据类型提示
            var hintText = '';
            if (documentType === '产品生产') {
                hintText = '<i class="layui-icon layui-icon-tips"></i> 当前显示【产品生产】工单数据';
                $('#dataTypeHint').css('color', '#1890ff');
            } else if (documentType === '生产领料') {
                hintText = '<i class="layui-icon layui-icon-tips"></i> 当前显示【生产领料】领料数据';
                $('#dataTypeHint').css('color', '#52c41a');
            } else {
                hintText = '<i class="layui-icon layui-icon-tips"></i> 生产领料显示领料数据，产品生产显示工单数据';
                $('#dataTypeHint').css('color', '#009688');
            }
            $('#dataTypeHint').html(hintText);
        }

        // 初始化饼状图
        function initPieChart(documentType, callback) {
            var chartDom = document.getElementById('pieChart');
            var myChart = echarts.init(chartDom);
            
            // 显示加载动画
            myChart.showLoading('default', {
                text: '数据加载中...',
                color: '#ff6b6b',
                textColor: '#000',
                maskColor: 'rgba(255, 255, 255, 0.8)',
                zlevel: 0
            });
            
            // 构建请求参数
            var params = {};
            if (documentType) {
                params.documentType = documentType;
            }
            
            // 请求真实接口数据
            $.ajax({
                url: '/Materialflowdata/GetPieChartData',
                type: 'GET',
                data: params,
                dataType: 'json',
                timeout: 10000,
                success: function(response) {
                    myChart.hideLoading();
                    if (response.code === 0 && response.data) {
                        showChartData(response.data);
                    } else {
                        // 接口返回失败，使用测试数据作为备用
                        useTestDataFallback();
                    }
                    if (callback) callback();
                },
                error: function() {
                    myChart.hideLoading();
                    // 接口请求失败，使用测试数据作为备用
                    useTestDataFallback();
                    if (callback) callback();
                }
            });
            
            function useTestDataFallback() {
                showNoData();
            }
            
            function showNoData() {
                myChart.setOption({
                    title: {
                        text: '暂无数据',
                        left: 'center',
                        top: 'center',
                        textStyle: {
                            color: '#999',
                            fontSize: 16
                        }
                    }
                });
            }
            
            function showChartData(responseData) {
                var data = responseData.data || [];
                var total = responseData.total || 0;
                
                if (data.length === 0) {
                    showNoData();
                    return;
                }

                // 构建标题
                var titleText = '物料流转占比';
                if (documentType) {
                    titleText += '-' + documentType;
                }

                // 饼状图配置
                var option = {
                    tooltip: {
                        trigger: 'item',
                        formatter: function(params) {
                            return params.name + '<br/>' +
                                   '数量: ' + params.value.toLocaleString() + '<br/>' +
                                   '占比: ' + params.percent + '%';
                        }
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        top: 'middle',
                        itemWidth: 14,
                        itemHeight: 14,
                        textStyle: {
                            fontSize: 12
                        }
                    },
                    series: [{
                        name: '物料流转',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        center: ['60%', '50%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 8,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: true,
                            position: 'outside',
                            fontSize: 12,
                            formatter: function(params) {
                                return params.name + '\n' + params.percent + '%';
                            }
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: 14,
                                fontWeight: 'bold'
                            },
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        labelLine: {
                            show: true
                        },
                        data: data.map(function(item, index) {
                            var colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#ffeaa7', '#dda0dd', '#98d8c8'];
                            return {
                                name: item.name,
                                value: item.value,
                                itemStyle: {
                                    color: colors[index % colors.length]
                                }
                            };
                        })
                    }]
                };

                myChart.setOption(option);
            }

            // 响应式处理
            window.addEventListener('resize', function() {
                myChart.resize();
            });
        }

        // 初始化柱状图
        function initBarChart(documentType, callback) {
            var chartDom = document.getElementById('barChart');
            var myChart = echarts.init(chartDom);
            
            // 显示加载动画
            myChart.showLoading('default', {
                text: '数据加载中...',
                color: '#009688',
                textColor: '#000',
                maskColor: 'rgba(255, 255, 255, 0.8)',
                zlevel: 0
            });
            
            // 构建请求参数
            var params = {};
            if (documentType) {
                params.documentType = documentType;
            }
            
            // 请求真实接口数据
            $.ajax({
                url: '/Materialflowdata/GetBarChartData',
                type: 'GET',
                data: params,
                dataType: 'json',
                timeout: 10000,
                success: function(response) {
                    myChart.hideLoading();
                    if (response.code === 0 && response.data) {
                        showChartData(response.data);
                    } else {
                        // 接口返回失败，使用测试数据作为备用
                        useTestDataFallback();
                    }
                    if (callback) callback();
                },
                error: function() {
                    myChart.hideLoading();
                    // 接口请求失败，使用测试数据作为备用
                    useTestDataFallback();
                    if (callback) callback();
                }
            });
            
            function useTestDataFallback() {
                showNoData();
            }
            
            function showNoData() {
                myChart.setOption({
                    title: {
                        text: '暂无数据',
                        left: 'center',
                        top: 'center',
                        textStyle: {
                            color: '#999',
                            fontSize: 16
                        }
                    }
                });
            }
            
            function showChartData(data) {
                var categories = Object.keys(data);
                var values = Object.values(data);
                
                if (categories.length === 0) {
                    showNoData();
                    return;
                }

                // 构建标题
                var titleText = '物料流转统计';
                if (documentType) {
                    titleText += '-' + documentType;
                }

                // 柱状图配置
                var option = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        },
                        formatter: function(params) {
                            var param = params[0];
                            return param.name + '<br/>' + 
                                   param.seriesName + ': ' + param.value.toLocaleString();
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '25%',
                        top: '20%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: categories,
                        axisLabel: {
                            interval: 0,
                            rotate: 45,
                            fontSize: 11
                        },
                        axisTick: {
                            alignWithLabel: true
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: 'TotalSum',
                        nameTextStyle: {
                            fontSize: 12
                        },
                        axisLabel: {
                            fontSize: 11,
                            formatter: function(value) {
                                return value.toLocaleString();
                            }
                        },
                        splitLine: {
                            lineStyle: {
                                type: 'dashed'
                            }
                        }
                    },
                    series: [{
                        name: 'TotalSum',
                        type: 'bar',
                        data: values,
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {offset: 0, color: '#40A9FF'},
                                {offset: 1, color: '#1890FF'}
                            ])
                        },
                        label: {
                            show: true,
                            position: 'top',
                            fontSize: 10,
                            formatter: function(params) {
                                return params.value.toLocaleString();
                            }
                        },
                        barWidth: '60%'
                    }]
                };

                myChart.setOption(option);
            }

            // 响应式处理
            window.addEventListener('resize', function() {
                myChart.resize();
            });
        }

        // 初始化折线图
        function initLineChart(documentType, callback) {
            var chartDom = document.getElementById('lineChart');
            var myChart = echarts.init(chartDom);
            
            // 显示加载动画
            myChart.showLoading('default', {
                text: '数据加载中...',
                color: '#52c41a',
                textColor: '#000',
                maskColor: 'rgba(255, 255, 255, 0.8)',
                zlevel: 0
            });
            
            // 构建请求参数
            var params = {};
            if (documentType) {
                params.documentType = documentType;
            }
            
            // 请求真实接口数据
            $.ajax({
                url: '/Materialflowdata/GetLineChartData',
                type: 'GET',
                data: params,
                dataType: 'json',
                timeout: 10000,
                success: function(response) {
                    myChart.hideLoading();
                    if (response.code === 0 && response.data) {
                        showChartData(response.data);
                    } else {
                        // 接口返回失败，使用测试数据作为备用
                        useTestDataFallback();
                    }
                    if (callback) callback();
                },
                error: function() {
                    myChart.hideLoading();
                    // 接口请求失败，使用测试数据作为备用
                    useTestDataFallback();
                    if (callback) callback();
                }
            });
            
            function useTestDataFallback() {
                showNoData();
            }
            
            function showNoData() {
                myChart.setOption({
                    title: {
                        text: '暂无数据',
                        left: 'center',
                        top: 'center',
                        textStyle: {
                            color: '#999',
                            fontSize: 16
                        }
                    }
                });
            }
            
            function showChartData(data) {
                var categories = Object.keys(data);
                var values = Object.values(data);
                
                if (categories.length === 0) {
                    showNoData();
                    return;
                }

                // 构建标题
                var titleText = '物料流转趋势';
                if (documentType) {
                    titleText += '-' + documentType;
                }

                // 折线图配置
                var option = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross'
                        },
                        formatter: function(params) {
                            var param = params[0];
                            return param.name + '<br/>' + 
                                   param.seriesName + ': ' + param.value.toLocaleString();
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '25%',
                        top: '20%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: categories,
                        axisLabel: {
                            interval: 0,
                            rotate: 45,
                            fontSize: 11
                        },
                        boundaryGap: false
                    },
                    yAxis: {
                        type: 'value',
                        name: 'TotalSum',
                        nameTextStyle: {
                            fontSize: 12
                        },
                        axisLabel: {
                            fontSize: 11,
                            formatter: function(value) {
                                return value.toLocaleString();
                            }
                        },
                        splitLine: {
                            lineStyle: {
                                type: 'dashed'
                            }
                        }
                    },
                    series: [{
                        name: 'TotalSum',
                        type: 'line',
                        data: values,
                        smooth: true,
                        symbol: 'circle',
                        symbolSize: 6,
                        lineStyle: {
                            width: 3,
                            color: '#52c41a'
                        },
                        itemStyle: {
                            color: '#52c41a',
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {offset: 0, color: 'rgba(82, 196, 26, 0.3)'},
                                {offset: 1, color: 'rgba(82, 196, 26, 0.1)'}
                            ])
                        },
                        label: {
                            show: true,
                            position: 'top',
                            fontSize: 10,
                            formatter: function(params) {
                                return params.value.toLocaleString();
                            }
                        }
                    }]
                };

                myChart.setOption(option);
            }

            // 响应式处理
            window.addEventListener('resize', function() {
                myChart.resize();
            });
        }
    </script>
</body>
</html>
